﻿Imports System.Data.SqlClient
Imports System.Data

Public Class Logon
    Inherits System.Web.UI.Page
    Dim myConnection As SqlConnection
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        myConnection = New SqlConnection("Data Source= (local);" _
                                         & "Database=Phonebook;Integrated Security=True")
    End Sub

    Protected Sub LoginButton_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
        Dim user As String = UserName.Text
        Dim passwd As String = Password1.Value

        Authentication(user, passwd)
    End Sub

    Sub Authentication(user As String, passwd As String)

        Dim queryString As String

        queryString = "SELECT PASSWD FROM USERS WHERE USERNAME = @user;"
        Dim querySql As SqlCommand = New SqlCommand(queryString, myConnection)
        querySql.Parameters.Add(New SqlParameter("@user", SqlDbType.NChar, 20))
        querySql.Parameters("@user").Value = user
        Try
            myConnection.Open()
            Dim reader As SqlDataReader = querySql.ExecuteReader()
            If (reader.HasRows) Then
                reader.Read()
                Dim validPasswd As String = reader(0).ToString.Trim
                If (validPasswd.Equals(passwd)) Then
                    Session("user") = user
                    reader.Close()
                    Response.BufferOutput = True
                    Response.Redirect("Home.aspx")
                Else
                    Message.Text = "The password is not valid. Please try again."
                End If
            Else
                Message.Text = "The user doesn't exist."
            End If
            reader.Close()
        Catch ex As Exception
            Message.Text = ex.Message

        End Try
        myConnection.Close()
    End Sub

    Protected Sub Password_TextChanged(sender As Object, e As EventArgs)

    End Sub


End Class